package io.simple.core;

import injections.annotations.Property;
import io.simple.core.chain.Transport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: rehak
 * Date: 8/20/13
 * Time: 3:34 PM
 * To change this template use File | Settings | File Templates.
 */
public class Server implements AutoCloseable {

    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);
    @Property(optional = true)
    private List<Transport> transports = new CopyOnWriteArrayList<>();

    public Server() {

    }

    public Server(Transport... transports) {
        if (transports == null) {
            transports = new Transport[0];
        }
        this.transports.addAll(Arrays.asList(transports));
    }

    public void start() {
        for (Transport t : transports) {
            try {
                t.start();
            } catch (Exception e) {
                LOGGER.error("Error starting transport " + t, e);
                System.exit(-1);
            }
        }
    }

    @Override
    public void close() throws Exception {
        for (Transport t : transports) {
            try {
                t.close();
            } catch (Exception e) {
                LOGGER.error("Error shutting down transport " + t, e);
            }
        }
    }
}
